package com.cloud.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloud.admin.common.constant.UserConstants;
import com.cloud.admin.common.exception.BusinessException;
import com.cloud.admin.common.utils.StringUtils;
import com.cloud.admin.mapper.SysRoleDeptMapper;
import com.cloud.admin.mapper.SysRoleMapper;
import com.cloud.admin.mapper.SysRoleMenuMapper;
import com.cloud.admin.mapper.SysUserRoleMapper;
import com.cloud.admin.model.entity.SysRole;
import com.cloud.admin.model.entity.SysRoleDept;
import com.cloud.admin.model.entity.SysRoleMenu;
import com.cloud.admin.model.entity.SysUserRole;
import com.cloud.admin.service.SysRoleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色信息表
 *
 * @author douhaichao code generator
 * @date 2019-07-09 10:27:00
 */
@Service
@AllArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final SysRoleMapper roleMapper;

    private final SysRoleMenuMapper roleMenuMapper;

    private final SysRoleDeptMapper roleDeptMapper;

    private final SysUserRoleMapper userRoleMapper;

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public SysRole selectOne(SysRole req) {
        QueryWrapper queryWrapper = new QueryWrapper<SysRole>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<SysRole> selectAll(SysRole req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<SysRole> selectPage(Page page, SysRole req) {
        IPage<SysRole> list = baseMapper.selectPage(
                page,
                new QueryWrapper<SysRole>().setEntity(req));
        return list;
    }

    /**
     * 根据对象查询所有分页数据(模糊查询)     *      * @return
     */
    @Override
    public IPage<SysRole> selectPageByLike(Page page, SysRole req) {

        IPage<SysRole> list = baseMapper.selectPage(page, getQueryWrapper(req));
        return list;
    }

    private QueryWrapper getQueryWrapper(SysRole req) {
        QueryWrapper queryWrapper = new QueryWrapper();

        if (null != req.getRoleId()) {
            queryWrapper.eq("role_id", req.getRoleId());
        }

        if (!StrUtil.isEmpty(req.getRoleName())) {
            queryWrapper.like("role_name", req.getRoleName());
        }

        if (!StrUtil.isEmpty(req.getRoleKey())) {
            queryWrapper.like("role_key", req.getRoleKey());
        }

        if (null != req.getRoleSort()) {
            queryWrapper.eq("role_sort", req.getRoleSort());
        }

        if (!StrUtil.isEmpty(req.getDataScope())) {
            queryWrapper.like("data_scope", req.getDataScope());
        }

        if (!StrUtil.isEmpty(req.getStatus())) {
            queryWrapper.like("status", req.getStatus());
        }

        if (!StrUtil.isEmpty(req.getDelFlag())) {
            queryWrapper.like("del_flag", req.getDelFlag());
        }

        if (!StrUtil.isEmpty(req.getCreateBy())) {
            queryWrapper.like("create_by", req.getCreateBy());
        }

        if (null != req.getCreateTime()) {
            queryWrapper.eq("create_time", req.getCreateTime());
        }

        if (!StrUtil.isEmpty(req.getUpdateBy())) {
            queryWrapper.like("update_by", req.getUpdateBy());
        }

        if (null != req.getUpdateTime()) {
            queryWrapper.eq("update_time", req.getUpdateTime());
        }

        if (!StrUtil.isEmpty(req.getRemark())) {
            queryWrapper.like("remark", req.getRemark());
        }
        return queryWrapper;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(SysRole req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRoleKeys(Long userId) {
        List<SysRole> perms = baseMapper.selectRolesByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<SysRole> selectRolesByUserId(Long userId) {
        List<SysRole> userRoles = baseMapper.selectRolesByUserId(userId);
        List<SysRole> roles = selectRoleAll();
        for (SysRole role : roles) {
            for (SysRole userRole : userRoles) {
                if (role.getRoleId() == userRole.getRoleId()) {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRoleAll() {
//        return SpringUtils.getAopProxy(this).selectRoleList(new SysRole());
        return selectRoleList(new SysRole());
    }

    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    public List<SysRole> selectRoleList(SysRole role) {
        return baseMapper.selectList(getQueryWrapper(role));
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public String checkRoleNameUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.ROLE_NAME_NOT_UNIQUE;
        }
        return UserConstants.ROLE_NAME_UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public String checkRoleKeyUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.ROLE_KEY_NOT_UNIQUE;
        }
        return UserConstants.ROLE_KEY_UNIQUE;
    }

    /**
     * 新增保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRole(SysRole role) {
        // 新增角色信息
        baseMapper.insert(role);
        return insertRoleMenu(role);
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRole(SysRole role) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(role);
        // 修改角色信息
        roleMapper.updateById(role);
        // 删除角色与菜单关联

        QueryWrapper del = new QueryWrapper();
        del.eq("role_id", role.getRoleId());
        roleMenuMapper.delete(del);

        return insertRoleMenu(role);
    }

    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int authDataScope(SysRole role) {
        // 修改角色信息
        baseMapper.updateById(role);
        // 删除角色与部门关联
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("role_id", role.getRoleId());
        roleDeptMapper.delete(queryWrapper);
        // 新增角色和部门信息（数据权限）
        return insertRoleDept(role);
    }

    /**
     * 批量删除角色信息
     *
     * @param ids 需要删除的数据ID
     * @throws Exception
     */
    @Override
    @Transactional
    public int deleteRoleByIds(String ids) throws BusinessException {
        Long[] roleIds = Convert.toLongArray(ids.split(","));
        for (Long roleId : roleIds) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("del_flag", "0");
            queryWrapper.eq("role_id", roleId);
            SysRole role = baseMapper.selectOne(queryWrapper);

            QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
            sysUserRoleQueryWrapper.eq("role_id", roleId);
            if (userRoleMapper.selectCount(sysUserRoleQueryWrapper) > 0) {
                throw new BusinessException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        QueryWrapper delRoleMenu = new QueryWrapper();
        delRoleMenu.in("role_id", roleIds);
        roleMenuMapper.delete(delRoleMenu);

        QueryWrapper<SysRole> delRole = new QueryWrapper<SysRole>();
        delRole.in("role_id", roleIds);
        return roleMapper.delete(delRole);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public int insertRoleMenu(SysRole role) {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId.intValue());
            list.add(rm);
        }
        if (list.size() > 0) {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public int insertRoleDept(SysRole role) {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : role.getDeptIds()) {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getRoleId());
            rd.setDeptId(deptId.intValue());
            list.add(rd);
        }
        if (list.size() > 0) {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }

    /**
     * 角色状态修改
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public int changeStatus(SysRole role) {
        return roleMapper.updateById(role);
    }

    /**
     * 取消授权用户角色
     *
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(SysUserRole userRole) {
        QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
        sysUserRoleQueryWrapper.setEntity(userRole);
        return userRoleMapper.delete(sysUserRoleQueryWrapper);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要删除的用户数据ID
     * @return 结果
     */
    public int deleteAuthUsers(Long roleId, String userIds) {
        return userRoleMapper.deleteUserRoleInfos(roleId, Convert.toLongArray(userIds));
    }

    /**
     * 批量选择授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要删除的用户数据ID
     * @return 结果
     */
    public int insertAuthUsers(Long roleId, String userIds) {
        Long[] users = Convert.toLongArray(userIds.split(","));
        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (Long userId : users) {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId.intValue());
            list.add(ur);
        }
        return userRoleMapper.insertBatchUserRole(list);
    }
}
